package com.eastmelon.blog.util;

import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.eastmelon.basic.model.SystemContext;
import com.eastmelon.blog.entity.Article;

public class LuceneUtil {
	public static Directory dir;
	public static String indexDir = SystemContext.getRealPath() + "/lucene";

	private static IndexWriter getWriter() throws Exception {
		// 获得中文分词器
		SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
		IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
		IndexWriter writer = new IndexWriter(dir, iwc);
		return writer;
	}

	public static void Indexer(Article article) throws Exception {
		dir = FSDirectory.open(Paths.get(indexDir));
		IndexWriter writer = getWriter();
		Document doc = new Document();
		String content=ContentUtil.delHTMLTag(article.getContent());
		// 加权操作
		if (article.getTitle() != null)
			doc.add(new TextField("title", article.getTitle(), Field.Store.YES));
		if (article.getContent() != null)
			doc.add(new TextField("content", content, Field.Store.YES));
		if (article.getPublishTime() != null)
			doc.add(new TextField("publishTime", article.getPublishTime(),
					Field.Store.YES));
		if (article.getArticlePic() != null)
			doc.add(new TextField("articlePic", article.getArticlePic(),
					Field.Store.YES));
		doc.add(new TextField("id", Integer.toString(article.getId()), Field.Store.YES));
		writer.addDocument(doc);
		writer.close();
	}

	public static List<Article> Searcher(String q)
			throws IOException, ParseException, InvalidTokenOffsetsException {
		List<Article> la = new ArrayList<Article>();
		Article article = new Article();
		Directory dir = FSDirectory.open(Paths.get(indexDir));
		IndexReader reader = DirectoryReader.open(dir);
		IndexSearcher is = new IndexSearcher(reader);
		SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();// 中文
		QueryParser parser = new QueryParser("content", analyzer);
		Query query = parser.parse(q);
		TopDocs hits = is.search(query, 10);
		// 显示得分高的片段
		QueryScorer scorer = new QueryScorer(query);
		Fragmenter fragmenter = new SimpleSpanFragmenter(scorer);
		SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter(
				"<b><font color='red'>", "</font></b>");
		Highlighter highlighter = new Highlighter(simpleHTMLFormatter, scorer);
		highlighter.setTextFragmenter(fragmenter);
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			Document doc = is.doc(scoreDoc.doc);
			String content = doc.get("content");
			String title = doc.get("title");
			String publishTime = doc.get("publishTime");
			String articlePic = doc.get("articlePic");
			int id = Integer.parseInt(doc.get("id"));
			if (content != null) {
				TokenStream tokenStream = analyzer.tokenStream("content",
						new StringReader(content));
				content = highlighter.getBestFragment(tokenStream, content);
			}
			article.setArticlePic(articlePic);
			article.setPublishTime(publishTime);
			article.setId(id);
			article.setTitle(title);
			article.setSummary(content);
			la.add(article);
		}
		reader.close();
		return la;
	}

	public static void delete(String id) throws Exception {
		dir = FSDirectory.open(Paths.get(indexDir));
		IndexWriter writer = getWriter();
		writer.deleteDocuments(new Term("id", id));
		writer.close();
	}

	public static void update(Article a) throws Exception {
		dir = FSDirectory.open(Paths.get(indexDir));
		IndexWriter writer = getWriter();
		Document doc=new Document();
		String content=ContentUtil.delHTMLTag(a.getContent());
		doc.add(new TextField("id", Integer.toString(a.getId()), Field.Store.YES));
		if (a.getPublishTime() != null)
			doc.add(new TextField("publishTime", a.getPublishTime(), Field.Store.YES));
		if (a.getContent() != null)
			doc.add(new TextField("content", content, Field.Store.YES));
		if (a.getTitle() != null)
			doc.add(new TextField("title", a.getTitle(), Field.Store.YES));
		if (a.getArticlePic() != null)
			doc.add(new TextField("articlePic", a.getArticlePic(), Field.Store.YES));
		writer.updateDocument(new Term("id",Integer.toString(a.getId())),doc);
		writer.close();
	}

}
